<%@ page contentType="text/html;charset=UTF-8" %>
<%@ include file="/WEB-INF/views/include/taglib.jsp" %>
<style>
    .panel-primary > .bc {
        background: linear-gradient(to bottom, #76A7B9, #2CBBA1);
    }
</style>
<script>
    var cardNo = "";//卡号
    var cardPayFlag = "";
    var medicalCardFlag = false;
    var medicalVsPatient = {};
    $(function () {
        $.ajaxSetup({ cache: false });
        //读idCard
        $("#readIdCard").on("click", function () {
            //读取
            var str = FindReader_onclick();
            if (str == "1") {
                toastr.error("没有找到读卡器！");
                return false;
            } else {
                //找到读卡器
                ReadCard_onclick();//写入数据
                $("#idNo").attr("disabled", "disabled");
                $("#name").attr("disabled", "disabled");
                var idNo = $("#idNo").val();
                if (!idNo) {
                    toastr.error("读卡失败");
                    return false;
                }
                return false;

            }
        });
        //读卡
        $("#readCard").on("click", function () {
            cardNo = readOneCard();
            if (!cardNo) {
                toastr.error("读卡失败");
                return false;
            } else {
                // 根据卡号查询卡信息
                findByCardNo(cardNo);
                return false;
            }
        });
        // 读取社保卡
        $("#readMed").on("click", function () {
            var returnVal = noInParams("getPersonInfo");
            if (returnVal.idNo != null && returnVal.idNo.length > 0) {
                medicalCardFlag = true;
                medicalVsPatient = returnVal;
            }

        })
    })
    function selectReg(hed, currentRegisNum, limtNum) {
        if (limtNum != 0) {
            if (Number(currentRegisNum) >= Number(limtNum)) {
                toastr.warning("此号已经挂满不能再挂此号");
                return false;
            }
        }
        if ($(hed).is(".bc")) {
            $(hed).removeClass("bc")
        } else {
            $(hed).addClass("bc");
        }
    }
    var totalPrice = 0.00;
    //保存挂号信息
    function saveReg() {
        if (!$('#inputForm').parsley().validate()) {
            return false;
        }
        var idNO = $("#idNo").val();
        if (idNO != null && idNO != '') {//根据身份证计算年龄
            var myDate = new Date();
            var month = myDate.getMonth() + 1;
            var day = myDate.getDate();
            var age = myDate.getFullYear() - idNO.substring(6, 10) - 1;
            if (idNO.substring(10, 12) < month || idNO.substring(10, 12) == month && idNO.substring(12, 14) <= day) {
                age++;
            }
            $("#age").val(age);
        }
        var clinic;
        $('#clinic header.bc input.simInput').each(function (index, element) {
            clinic = $(this).val();
        })
        if (clinic == null || clinic == 'undefined') {
            toastr.warning("请选择挂号类型");
            return false;
        }
        var regLen = $('#clinic header.bc');
        var labelHtml = "";
        var clinicIds = new Array();
        var prices = new Array();

        for (var i = 0; i < regLen.length; i++) {
            var clinicLabel = regLen.eq(i).find("#label").val();
            var price = regLen.eq(i).find("#price").val();
            price=Number(price).toFixed(2);
            var clinicId = regLen.eq(i).find("#clinicId").val();
            clinicIds.push(clinicId);
            prices.push(price);
            totalPrice +=Number(price);
            labelHtml += '<a href="javascript:;" class="list-group-item">' +
            '<span class="badge bg-primary pull-right">' + price + '</span>' +
            '' + clinicLabel + '</a>';
        }
        labelHtml+='<a href="javascript:;" class="list-group-item" style="color: red">' +
        '<span class="badge bg-primary pull-right">' + Number(totalPrice).toFixed(2)+ '</span>' +
        '合计</a>';

        labelHtml += ' <a href="javascript:;" class="list-group-item" style="color: red">' +
        '支付方式' +
        '<span class="pull-right">' +
        '<select name="payType" id="payType" class="form-control" data-parsley-required="true">' +
        <c:forEach items="${fns:getDictList('PAY_WAY_DICT')}" var="type">
        <c:choose>
        <c:when test="${type.label=='现金'}">
        '<option value="${type.value}" selected="selected">${type.label}</option>' +
        </c:when>
        <c:otherwise>
        '<option value="${type.value}">${type.label}</option>' +
        </c:otherwise>
        </c:choose>
        </c:forEach>
        '</select>' +
        '</span>' +
        '</a>' +
        '<div class="list-group-item">' +
        '实收:' +
        '<input type="number" name="identity" id="costs" class="form-control" min=0 onblur="theChange();"/>' +
        '找零:' +
        '<input name="identity" type="text" readonly="true" id="charges" class="form-control" onclick="theChange(' + totalPrice + ')"/>' +
        '</div>';
        $("#reg").html(labelHtml);
        $("#costs").val(Number(totalPrice).toFixed(2));
        var payType = $("#payType option:selected").val();
        if (isOpen()) {
            jQuery(document).bind('keydown', 'return',function (evt){
                checkMethod(clinicIds, prices);
                return false;
            });
            register = layer.open({
                title: '挂号结果',
                type: 1,
                area: ['30%', '60%'],
                content: $("#regResult"),
                btn: ['确定', '取消'],
                yes: function (index, layero) {
                    checkMethod(clinicIds, prices);

                },
                end: function () {
                    totalPrice = 0.0;
                }
            });
        } else {
            $("#cardPayFlag").val(0);
            ajaxData(clinicIds, prices, '3', medicalCardFlag);
        }

    }
    function checkMethod(clinicIds, prices){
        var payType = $("#payType").val();
        if (3 == payType) {
            var balance = $("#balance").val();
            if (balance.length == 0) {
                cardPayFlag = 1;
                toastr.warning("一卡通读取错误!");
                return false;
            } else {
                if (balance < totalPrice) {
                    toastr.warning("一卡通余额不足,请缴纳现金!");
                    cardPayFlag = 1;
                    return false;
                } else {
                    cardPayFlag = 0;
                }
            }
        } else {
            cardPayFlag = 1;
        }
        var costs = $("#costs").val();
        if (costs==null || costs == '') {
            toastr.warning("实收金额不能为空");
            return;
        }
        if (costs != null && costs != '') {
            if (costs < totalPrice) {
                toastr.warning("实收金额小于总价");
                return;
            }
        }
        $("#cardPayFlag").val(cardPayFlag);
        ajaxData(clinicIds, prices, payType, medicalCardFlag);
    }
    function ajaxData(clinicIds, prices, payType, medicalCardFlag) {
        var url = '${ctx}/oper/patMasterIndex/save?clinicIds=' + clinicIds + '&prices=' + prices + '&payType=' + payType;
        if (medicalCardFlag) {
            url = '${ctx}/oper/patMasterIndex/save?clinicIds=' + clinicIds + '&prices=' + prices + '&payType=' + payType + "&medicalVsPatient=" + medicalVsPatient;
        }
        if (flag) {
            flag = false;
            $.ajax({
                type: 'post',
                url: url,
                data: $('#inputForm').serialize(),
                success: function (data) {
                    if (data != null) {
                        toastr.success("挂号成功");
                        if(isOpen()){
                            layer.close(register);
                        }
                        for (var i = 0; i < data.length; i++) {
                            var printId = data[i].id;
                            printPdf('${ctx}/oper/patMasterIndex/printRegisit', 'id=' + printId);
                        }
                        loadDiv('mainCenterDiv', '${ctx}/oper/patMasterIndex/todayRegister');
                    } else {
                        flag = true;
                    }
                }
            });

        }

    }
    function isOpen() {
        var returnVal = true;
        var balance = $("#balance").val();
        if (balance.length == 0) {
            cardPayFlag = 1;
        } else {
            if (balance < totalPrice) {
                toastr.warning("一卡通余额不足,请缴纳现金挂号!");
//                cardPayFlag=1;
//                return false;
            } else {
                returnVal = false;
            }
        }
        return returnVal;
    }
    var registFlag = true;


    function theChange() {
        var regexNumber = /^\d+(.\d{1,4})?$/;
        var costs = $("#costs").val();
        if (!regexNumber.test(costs)) {
            toastr.warning("请输入有效数字");
            return false;
        }
        if (costs != null && costs != '') {
            if (costs < totalPrice) {
                toastr.warning("实收金额小于总价");
                return;
            } else {
                $("#charges").val(Number(costs - totalPrice).toFixed(2));
            }
        }
    }
    //检索唯一标识
    jQuery("#name").bind('keydown', 'return',function (evt){
        var name = $("#name").val();
        patientInfo = layer.open({
            type: 2,
            title: '病人列表',
            shadeClose: true,
            shade: 0.8,
            area: ['80%', '80%'],
            content: '${ctx}/oper/patMasterIndex/retrievePatMaster?name=' + name
        });
        return false;
    });
    //回写基本信息
    function assignment(patId, name, sex, age, chargeType, identity, idNo, unitInContract) {
        $("#patientId").val(patId);
        $("#name").val(name);
        if (sex != null && sex != "") {
            $("#sexID option[value=" + sex + "]").attr("selected", "selected");
            $("#sexID").change();
        }
        $("#age").val(age);
        $("#visitIndicator option[value='2']").attr("selected", "selected");
        $("#visitIndicator").change();
        if (chargeType != null && chargeType != "") {
            $("#chargeType option[value=" + chargeType + "]").attr("selected", "selected");
            $("#chargeType").change();
        }
        if (identity != null && identity != "") {
            $("#identity option[value=" + identity + "]").attr("selected", "selected");
            $("#identity").change();
        }
        $("#idNo").val(idNo);
        $("#unitInContract").val(unitInContract);
        layer.close(patientInfo);
    }
    function findByCardNo(cardNo) {
//    alert("cardNo="+cardNo);
        $.ajax({
            type: "post",
            url: "/a/med/medicalCardMaster/findByCardNo?cardNo=" + cardNo,
            data:{r:Math.random()},
            dataType: "json",
            cache: false,
            success: function (data) {
                if(data){
                    //输入框输入值
                    $("#name").val(data.name);
                    $("#sex option[value=" + data.sex + "]").attr("selected", "selected");
                    $("#sex").change();
                    $("#sexID option[value=" + data.sex + "]").attr("selected", "selected");
                    $("#sexID").change();
                    $("#age").val(data.age);
                    $("#idNo").val(data.idCard);
                    $("#idCard").val(data.idCard);
                    $("#nation option[value=" + data.nation + "]").val(data.nation);
                    $("#nation").change();
                    $("#chargeType option[value=" + data.expand1 + "]").attr("selected", "selected");
                    $("#chargeType").change();
                    $("#balance").val(data.balance);
                    $("#patientId").val(data.patientId);
                    $("#cardNo").val(cardNo);
                }else{
                    toastr.error("根据卡号读取信息错误！");
                }

            },
            error: function (data) {
                toastr.error("根据卡号读取信息错误！");
            }
        });
    }
</script>
<div class="app">
    <section class="layout">
        <aside class="col-lg-9 canvas-right bg-default pl0">
            <header class="header navbar clearfix bb bg-default pl10 pr0">
                <div class="pull-left">
                    <form:form id="searchForm" class="form-inline" style="padding-top: 10px" modelAttribute="cRegist"
                               onsubmit="return loadDivForm('mainCenterDiv','searchForm','${ctx}/oper/patMasterIndex/todayRegister')">
                        门诊号别 ：<form:input path="clinicLabel" class="form-control" keyup="$('#searchForm').submit()"/>
                        门诊科室 ：<form:input path="deptId" class="form-control" keyup="$('#searchForm').submit()"/>&nbsp;&nbsp;
                        <input id="search" class="btn btn-primary" type="submit" value="查询"/>&nbsp;&nbsp;
                        <input id="readCard" class="btn btn-primary" type="submit" value="读卡"/>&nbsp;
                        <%--<input id="readMed" class="btn btn-primary" type="submit" value="读取社保卡"/>&nbsp;--%>
                        <input id="readIdCard" class="btn btn-primary" type="submit" value="读取身份证"/>
                    </form:form>
                </div>
            </header>
            <div class="content-wrap no-p">
                <div class="wrapper" style="bottom: 40px;">
                    <c:forEach items="${list}" var="clinicForReg">
                        <div class="col-md-4" id="clinic">
                            <section class="panel panel-primary no-b">
                                <header class="panel-heading clearfix brtl brtr"
                                        onclick="selectReg(this,'${clinicForReg.currentRegisNum}','${clinicForReg.limitNum}')">
                                    <div class="overflow-hidden">
                                        <a href="javascript:;"
                                           class="h4 show no-m pt10 pull-left">${clinicForReg.clinicLabel}</a>
                                        <span class="badge pull-right bg-success">${clinicForReg.inputCode}</span>
                                            <%--<a href="javascript:;" class="h4 show no-m pt10">医生：</a>--%>
                                        <input type="hidden" id="clinicId" class="simInput" value="${clinicForReg.id}">
                                        <input type="hidden" id="deptId" value="${clinicForReg.deptId}">
                                        <input type="hidden" id="doctor" value="${clinicForReg.doctorId}">
                                        <input type="hidden" id=label value="${clinicForReg.clinicLabel}">
                                        <input type="hidden" id="price" value="${clinicForReg.price}">
                                    </div>
                                </header>
                                <div class="list-group">
                                    <a href="javascript:;" class="list-group-item">
                                        <i class="ti-comment mr10 text-muted"></i>${clinicForReg.deptId}
                                    </a>
                                    <a href="javascript:;" class="list-group-item">
                                        <i class="ti-calendar mr10 text-muted"></i>${fns:getDictLabel(clinicForReg.timeDesc, 'TIME_OF_DAY', '')}
                                    </a>
                                    <a href="javascript:;" class="list-group-item">
                                        <i class="ti-bell mr10 text-muted"></i>${clinicForReg.currentRegisNum}/${clinicForReg.limitNum}
                                    </a>
                                </div>
                            </section>
                        </div>
                    </c:forEach>
                    <div class="col-md-8 " id="regResult" style="display: none">
                        <section class="panel panel-primary no-b">
                            <div class="list-group" id="reg">

                            </div>

                        </section>
                    </div>
                </div>
            </div>
        </aside>
        <!-- /mail sidebar navigation -->

        <!-- main content -->
        <section class="main-content" id="rigthCenterDiv">
            <div class="content-wrap">
                <div class="wrapper">
                    <ul class="nav nav-tabs">
                        <li class="active">
                            <a href="#">基本信息</a>
                        </li>
                    </ul>
                    <section class="panel panel-default">
                        <div class="panel-body">
                            <div class="col-lg-12">
                                <form id="inputForm" class="form-horizontal" data-parsley-validate="">
                                    <input type="hidden" id="patientId" name="id">
                                    <input type="hidden" id="cardPayFlag" name="cardPayFlag">
                                    <input type="hidden" id="cardNo" name="cardNo">

                                    <div class="form-group">
                                        <label class="col-sm-4 control-label">姓名：</label>

                                        <div class="col-sm-8">
                                            <input name="name" id="name" class="form-control"
                                                   data-parsley-required="true"/>
                                        </div>
                                    </div>
                                    <div class="form-group">
                                        <label class="col-sm-4 control-label">性别：</label>

                                        <div class="col-sm-8">
                                            <select name="sex" class="form-control" id="sexID"
                                                    data-parsley-required="true">
                                                <c:forEach items="${fns:getDictList('SEX_DICT')}" var="sex">
                                                    <option value="${sex.value}">${sex.label}</option>
                                                </c:forEach>
                                            </select>
                                        </div>
                                    </div>
                                    <div class="form-group">
                                        <label class="col-sm-4 control-label">年龄：</label>

                                        <div class="col-sm-8">
                                            <input type="number" id="age" name="age" class="form-control"
                                                   data-parsley-required="true" maxlength="3" min="0"/>
                                        </div>
                                    </div>
                                    <div class="form-group">
                                        <label class="col-sm-4 control-label">诊别：</label>

                                        <div class="col-sm-8">
                                            <select name="firstVisitIndicator" class="form-control" id="visitIndicator">
                                                <c:forEach items="${fns:getDictList('first_visit_indicator')}"
                                                           var="firstVisit">
                                                    <option value="${firstVisit.value}">${firstVisit.label}</option>
                                                </c:forEach>
                                            </select>
                                        </div>
                                    </div>
                                    <div class="form-group">
                                        <label class="col-sm-4 control-label">费别：</label>

                                        <div class="col-sm-8">
                                            <%-- <input name="chargeType" class="form-control"  maxlength="100" />--%>
                                            <select name="chargeType" class="form-control" id="chargeType">
                                                <c:forEach items="${fns:getDictList('CHARGE_TYPE_DICT')}"
                                                           var="chargeType">
                                                    <c:choose>
                                                        <c:when test="${chargeType.value}">
                                                            <option value="${chargeType.value}"
                                                                    selected="selected">${chargeType.label}</option>
                                                        </c:when>
                                                        <c:otherwise>
                                                            <option value="${chargeType.value}">${chargeType.label}</option>
                                                        </c:otherwise>
                                                    </c:choose>

                                                </c:forEach>
                                            </select>
                                        </div>
                                    </div>
                                    <div class="form-group">
                                        <label class="col-sm-4 control-label">身份：</label>

                                        <div class="col-sm-8">
                                            <select name="identity" class="form-control" id="identity">
                                                <c:forEach items="${fns:getDictList('PROFESSION_DICT')}"
                                                           var="profession">
                                                    <option value="${profession.value}">${profession.label}</option>
                                                </c:forEach>
                                            </select>
                                        </div>
                                    </div>
                                    <div class="form-group">
                                        <label class="col-sm-4 control-label">身份证号：</label>

                                        <div class="col-sm-8">
                                            <input name="idNo" id="idNo" class="form-control"
                                                   data-parsley-checkidcard="3" maxlength="100"/>
                                        </div>
                                    </div>
                                    <%--<div class="form-group">--%>
                                    <%--<label class="col-sm-4 control-label">合同单位：</label>--%>

                                    <%--<div class="col-sm-8">--%>
                                    <%--<input name="unitInContract" id="unitInContract" class="form-control"--%>
                                    <%--maxlength="100"/>--%>
                                    <%--</div>--%>
                                    <%--</div>--%>
                                </form>
                                <div class="form-group">
                                    <div class="col-sm-offset-2 col-sm-10">
                                        <input id="btnSubmit" class="btn btn-primary" type="submit" value="保 存"
                                               onclick="saveReg();">&nbsp;
                                    </div>
                                </div>
                            </div>
                        </div>
                    </section>
                </div>
            </div>
        </section>
        <!-- /main content -->
        <input type="hidden" id="balance" value=""/>
    </section>
</div>